<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>密码显示与隐藏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        .box {
            display: flex;
        }

        .inpt {
            position: relative;
            width: 32px;
            height: 16px;
        }

        .yc {
            position: absolute;
            right: 0;
            top: 0;
            display: none;
        }
    </style>
</head>

<body>
    <div class="box">
        <input type="password" placeholder="请输入密码">
        <div class="inpt">
            <button class="xs">显示</button>
            <!-- <button class="yc">隐藏</button> -->
        </div>
    </div>





    <script>
        // 获取dom标签元素
        const inpt = document.querySelector('input');
        const btnxs = document.querySelector('.xs');
        const btnyc = document.querySelector('.yc');
        // 设置初始值，区分点击事件
        let flag = true;

        // 给显示点击按钮绑定点击事件
        btnxs.addEventListener('click', function (e) {
            /* inpt.type = 'text';
            this.style.display = 'none';
            btnyc.style.display = 'block'; */
            if (flag) {
                inpt.type = 'text';
                btnxs.innerHTML = '隐藏';

            } else {
                inpt.type = 'password';
                btnxs.innerHTML = '显示';
            }
            flag = !flag;
        });

        // 方法二 用两个按钮做，点击时隐藏自身，显示另外一个按钮
        /* // 给隐藏点击按钮绑定点击事件
        btnyc.addEventListener('click', function (e) {
            inpt.type = 'password';
            this.style.display = 'none';
            btnxs.style.display = 'block';
        }); */

    </script>
</body>

</html>